<template>
  <page-view class="register">
    <page-header
      title="修改资料"
      :show-back="true"
      class="header"
    ></page-header>
    <div class="content-box">
      <van-form ref="registerForm">
        <van-cell-group inset>
          <van-field
            v-model="userInfoForm.nickName"
            name="nickName"
            label="昵称"
            placeholder="请输入昵称"
            :rules="[
              { required: true, message: '请填写昵称', trigger: 'onBlur' },
              {
                validator: validatorNick,
                message: '昵称不可用',
                trigger: 'onBlur',
              },
            ]"
          />
          <!-- required 必填项 -->
          <!-- pattern 通过正则表达式进行校验，正则无法匹配表示校验不通过 -->
          <!-- validator 通过函数进行校验，可以返回一个 Promise 来进行异步校验 -->
          <van-field
            v-model="userInfoForm.password"
            type="password"
            name="password"
            label="密码"
            placeholder="请输入密码"
            :rules="[
              { required: true, message: '请填写密码', trigger: 'onBlur' },
              {
                validator: validatorPassword,
                message: '密码格式不符合要求',
                trigger: 'onBlur',
              },
            ]"
          />
          <van-field
            v-model="userInfoForm.confirm_pwd"
            type="password"
            name="confirm_pwd"
            label="确认密码"
            placeholder="请再次输入密码"
            :rules="[
              { required: true, message: '请填写确认密码', trigger: 'onBlur' },
              {
                validator: validatorConfirm,
                message: '确认密码不一致，请重新输入',
                trigger: 'onBlur',
              },
            ]"
          />
          <van-field
            v-model="userInfoForm.user_phone"
            type="text"
            name="user_phone"
            label="手机号"
            placeholder="请输入手机号"
            :rules="[
              { required: true, message: '请填写手机号', trigger: 'onBlur' },
              {
                pattern:
                  /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
                message: '手机号码输入错误',
              },
              {
                validator: validatorPhone,
                message: '手机号不可用',
                trigger: 'onBlur',
              },
            ]"
          />
          <van-field
            v-model="userInfoForm.user_email"
            type="text"
            name="user_email"
            label="邮箱"
            placeholder="请输入邮箱"
            :rules="[
              { required: true, message: '请填写邮箱', trigger: 'onBlur' },
              {
                pattern:
                  /^([a-zA-Z\d][\w-]{2,})@(\w{2,})\.([a-z]{2,})(\.[a-z]{2,})?$/,
                message: '邮箱格式错误，请检查',
              },
            ]"
          />
          <van-field name="user_sex" label="性别">
            <!-- 具名插槽 -->
            <template #input>
              <!-- 组 -->
              <van-radio-group
                v-model="userInfoForm.user_sex"
                direction="horizontal"
              >
                <van-radio name="男">男</van-radio>
                <van-radio name="女">女</van-radio>
              </van-radio-group>
            </template>
          </van-field>
          <van-field
            name="uploader"
            label="用户头像"
            v-model="userInfoForm.user_photo"
            :rules="[
              { required: true, message: '请上传头像', trigger: 'onBlur' },
            ]"
          >
            <template #input>
              <van-uploader
                v-model="fileList"
                :after-read="afterRead"
                :max-count="1"
              />
            </template>
          </van-field>
        </van-cell-group>
        <div style="margin: 16px">
          <van-button
            round
            block
            type="primary"
            :loading="isSubmiting"
            loading-text="修改中。。。"
            :disabled="isSubmiting"
            @click="submitRegister"
          >
            提交
          </van-button>
        </div>
      </van-form>
    </div>
  </page-view>
</template>

<script setup>
import { reactive, ref, inject, toRaw } from "vue";
import Api from "../utils/api";
import { Notify } from "vant";
import { useRouter, useRoute } from "vue-router";
import { useStore } from "vuex";
import MD5 from "md5.js";
const router = useRouter();
const route = useRoute();
const store = useStore();
// 头像上传
const fileList = ref([]);
const BaseURL = inject("BaseURL");
const isSubmiting = ref(false);
const userInfoForm = reactive({
  nickName: store.state.userInfo.nickName,
  user_sex: store.state.userInfo.user_sex,
  user_phone: store.state.userInfo.user_phone,
  user_email: store.state.userInfo.user_email,
  user_photo: store.state.userInfo.user_photo,
  password: store.state.userInfo.password,
  confirm_pwd: "",
});
const registerForm = ref(null);

// 异步验证
const validatorNick = async (val) => {
  if (val == store.state.userInfo.nickName) {
    return true;
  }
  let results = await Api.userInfo.checkNickName(val);
  if (results.status === "fail") return false;
  else if (val.trim() === "") return "昵称不能为空";
};
const validatorPhone = async (val) => {
  if (val == store.state.userInfo.user_phone) {
    return true;
  }
  let results = await Api.userInfo.checkUserPhone(val);
  console.log(results);
  if (results.status === "fail") return false;
  else if (val.trim() === "") return "手机号不能为空";
};
const validatorPassword = async (val) => {
  if (val == store.state.userInfo.user_phone) {
    return true;
  }
  if (val.trim() === "") return "密码不能为空";
  else if (val.length < 6 || val.length > 19) return "密码长度应在6~18之间";
};
const validatorConfirm = async (val) => {
  let password = toRaw(userInfoForm.password);
  if (val != password) return false;
};

const afterRead = async (file) => {
  // 此时可以自行将文件上传至服务器
  //   console.log(file);
  let results = await Api.userInfo.uploadUserPhoto(file.file);
  // console.log(results);
  userInfoForm.user_photo = results;
  store.state.userInfo.user_photo = userInfoForm.user_photo;
};

const submitRegister = async () => {
  try {
    await registerForm.value.validate();
    isSubmiting.value = true;
    let { nickName, user_sex, user_phone, user_email, user_photo, password } =
      userInfoForm;
    password = new MD5().update(password).digest("hex");
    let results = Api.userInfo.register({
      nickName,
      user_sex,
      user_phone,
      user_email,
      user_photo,
      password,
    });
    Notify({ type: "success", message: "修改成功" });
    router.replace({ name: "Login" });
  } catch (error) {
    console.log(error);
  } finally {
    isSubmiting.value = false;
  }
};
</script>

<style lang="scss" scoped>
</style>